package com.java.softproblem.exer1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 银行有一个账户，
 * 有两个储户分别向这个账户存3000元，每次存一千，分三次，每次存完打印账户余额
 * <p>
 * 分析：
 * 1.是否是多线程问题？   是
 * 2.多个线程分别是谁？   储户一；储户二
 * 3.是多线程就一定会涉及到线程安全问题吗？   考虑是否有共享数据
 * 4.是否有共享数据呢？         有  账户或账户余额
 * 5.如何解决线程安全问题 ？  同步机制：有三种方式解决  、 同步代码块、同步方法  、lock锁
 *
 * @author luzhikun
 * @date &{DATE}-17:18
 */
public class CustormerTest {
    public static void main(String[] args) {


        Account account = new Account(0);
        Customer1 customer1 = new Customer1(account);
        Customer1 customer11 = new Customer1(account);


        customer1.setName("储户一");
        customer11.setName("储户二");

        customer1.start();
        customer11.start();
//        Customer customer=new Customer();
//        Thread thread = new Thread(customer);
//        thread.setName("储户一");
//        Thread thread1=new Thread(customer);
//        thread1.setName("储户二");
//        thread.start();
//        thread1.start();
    }
}

//class Customer implements Runnable{
//    private int money=0;
//    @Override
//    public void run() {
//        synchronized (this) {
//            for (int i = 0; i < 3; i++) {
//                money += 1000;
//                System.out.println(Thread.currentThread().getName()+"，存钱成功，余额为："+money);
//            }
//        }
//    }
//}
class Customer1 extends Thread {


    private static Account account;

    public Customer1(Account account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 3; i++) {
            account.deposit(1000);
        }
    }
}

class Account {
    private static int money;
    private static ReentrantLock lock = new ReentrantLock(true);

    public Account(int money) {
        this.money = money;
    }

    //方式一：同步方法
    //   public synchronized void deposit(double amt){
//       if (amt>0){
//
//           money+=amt;
//           try {
//               Thread.sleep(1000);
//           } catch (InterruptedException e) {
//               e.printStackTrace();
//           }
//           System.out.println(Thread.currentThread().getName()+"存钱成功"+money);
//       }
//
//   }
    //方式二：lock锁
    public void deposit(double amt) {
        try {
            if (amt > 0) {
                lock.lock();
                money += amt;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "存钱成功" + money);
            }
        } finally {
            lock.unlock();
        }

    }
}
